package com.geek.novel.utils

import android.text.TextUtils
import com.geek.novel.common.Constant
import com.geek.novel.entity.SysUser
import com.geek.novel.services.ImageService

class SecurityUtil {

    companion object{
        fun getPrincipal(): SysUser? {
            val jsonString = SPUtil[Constant.SP_USERINFO, SPUtil.usrInfo] as String
            if(TextUtils.isEmpty(jsonString)){
                return null
            }
            return GsonUtil.fromJson(jsonString, SysUser::class.java)
        }
        fun setPrincipal(user: SysUser){
            val jsonString = GsonUtil.toJson(user)
            SPUtil.put(Constant.SP_USERINFO, jsonString, SPUtil.usrInfo)
        }
        fun logout(){
			//删除用户本地头像
			ImageService.deleteUserImage()
			
			//登出
			SPUtil.remove(Constant.SP_TOKEN, SPUtil.usrInfo)
			SPUtil.remove(Constant.SP_USERINFO, SPUtil.usrInfo)
        }

        /**超级管理员权限*/
        fun hasRoleSuAdmin(): Boolean{
            return hasRole(Constant.ROLE_SU_ADMIN)
        }
        /**管理员、超级管理员权限*/
        fun hasRoleAdmin(): Boolean{
            if(hasRoleSuAdmin()){
                return true
            }
            return hasRole(Constant.ROLE_ADMIN)
        }

        private fun hasRole(roleCode: String): Boolean{
            val user = getPrincipal()
            if(user != null){
                return user.hasRole(roleCode)
            }
            return false
        }
    }

}